import React,{Component} from 'react';
import {
    View,
    StyleSheet,
    WebView,
    TouchableOpacity,
    Text,
    AppState,
    BackHandler,
    ToastAndroid,
    Platform,
    NativeModules,
    Clipboard
} from 'react-native'
import splash from 'react-native-splash-screen';
import RNExitApp from 'react-native-exit-app';
let refWebview = null;
let firstClick = 0;
export default class App extends Component{
    constructor(props){
        super(props);
        this.state = {
            webError:false,
            url:"http://47.75.103.157:39886?t="+new Date()
        }
        AppState.addEventListener('change', (e)=>this.handleAppStateChange(e));
        BackHandler.addEventListener("hardwareBackPress",()=>this.onBackPress())
    }
    componentWillUnmount(){
        BackHandler.removeEventListener('hardwareBackPress')
    }
    onBackPress(){
        if(Platform.OS == "android"){
            var timestamp = (new Date()).valueOf();
            if (timestamp - firstClick > 2000) {
                firstClick = timestamp;
                ToastAndroid.show('再按一次退出', ToastAndroid.SHORT);
                return true;
            } else {
                RNExitApp.exitApp();
                return false;
            }
        }
    }
    componentWillMount(){
      setTimeout(() => {
        splash.hide();
      }, 2000);
    }
    handleAppStateChange(state){
        if(state == "background"){
            RNExitApp.exitApp();
        }
    }
    render(){
        let {webError,url} = this.state;
        return (
            <View style = {{flex:1}}>
                <View style = {styles.content}>
                    {
                        webError?
                        <View style = {styles.errorView}>
                            <TouchableOpacity
                                onPress = {()=>this.webViewReload()}
                                activeOpacity = {0.8}
                                >
                                <Text style = {{fontSize:15,color:"#333"}}>加载失败？点击重试</Text>
                            </TouchableOpacity>
                        </View>
                        :<WebView
                            automaticallyAdjustContentInsets={false}
                            style={styles.webView}
                            source={{uri:url}}
                            javaScriptEnabled={true}
                            domStorageEnabled={true}
                            decelerationRate="normal"
                            ref = {ref=>this.onRef(ref)}
                            onMessage = {(d)=>this.onMessage(d)}
                            startInLoadingState={true}
                            onError = {(e)=>this.onError(e)}
                        />
                    }
                </View>
            </View>
        )
    }
    onError(){
        splash.hide();
        this.setState({
            webError:true
        })
    }
    showLoading(){
        console.log(this)
    }
    onRef(ref){
        refWebview = ref;
    }
    onMessage(d){
        try{
            let jsonData = JSON.parse(d.nativeEvent.data);
            switch (jsonData.type) {
                case "clipboard":
                    Clipboard.setString(jsonData.text);
                    refWebview && refWebview.injectJavaScript("clipboardcall(1)")
                    break;
                default:
                    break;
            }
        }catch(e){
            refWebview && refWebview.injectJavaScript("clipboardcall(0)")
        }
    }
    webViewReload(){
        let url = this.state.url;
        this.setState({
            webError:false,
            url:url
        },()=>{
            refWebview.reload();
        })
    }
}

const styles = StyleSheet.create({
    content:{
        flex:1
    },
    webView:{
        flex:1
    },
    errorView:{
        flex:1,
        backgroundColor: "#f2f2f2",
        position: "absolute",
        top:0,
        left:0,
        right:0,
        bottom:0,
        justifyContent: 'center',
        alignItems: 'center',
    }
})